package com.jappit.runtracker.model;

import java.util.Date;
import java.util.Vector;

import com.nokia.maps.common.GeoBoundingBox;
import com.nokia.maps.common.GeoCoordinate;

public class Run
{
	public int rmsId = -1;
	
	Date startDate = null;
	Date endDate = null;
	
	float distance = 0;
	
	Vector coordinates = null;
	GeoCoordinate lastCoordinate = null;
	
	public Run()
	{
		coordinates = new Vector();
	}
	public void start()
	{
		startDate = new Date();
	}
	public void stop()
	{
		endDate = new Date();
	}
	public long getDuration()
	{
		if(this.isStarted())
		{
			if(this.isEnded())
			{
				return endDate.getTime() - startDate.getTime();
			}
			else
			{
				return new Date().getTime() - startDate.getTime();
			}
		}
		return 0;
	}
	
	public double getAverageSpeed()
	{
		long duration = this.getDuration();
		double distance = this.getDistance();
		
		double averageSpeed = distance * 3600000 / duration;
		
		return averageSpeed;
	}
	public void addCoordinate(GeoCoordinate coordinate)
	{
		if(lastCoordinate != null)
		{
			distance += lastCoordinate.distanceTo(coordinate);
		}
		lastCoordinate = coordinate;
		
		coordinates.addElement(coordinate);
	}
	public float getDistance()
	{
		return distance;
	}
	public void setDistance(float distance)
	{
		this.distance = distance;
	}
	public Date getStartDate()
	{
		return startDate;
	}
	public void setStartDate(Date date)
	{
		this.startDate = date;
	}
	public Date getEndDate()
	{
		return endDate;
	}
	public void setEndDate(Date date)
	{
		this.endDate = date;
	}
	public Vector getCoordinates()
	{
		return coordinates;
	}
	public int getCoordinatesNum()
	{
		return coordinates.size();
	}
	public GeoCoordinate getCoordinate(int index)
	{
		return (GeoCoordinate)coordinates.elementAt(index);
	}
	public GeoCoordinate getLastCoordinate()
	{
		return lastCoordinate;
	}
	public boolean isStarted()
	{
		return startDate != null;
	}
	public boolean isEnded()
	{
		return endDate != null;
	}
	public GeoBoundingBox getBoundingBox()
	{
		GeoCoordinate current = null;
		GeoBoundingBox bbox = null;
		
		for(int i = 0, num = coordinates.size(); i < num; i++)
		{
			current = getCoordinate(i);
			
			if(bbox == null)
			{
				bbox = new GeoBoundingBox(current, current);
			}
			else
			{
				bbox = bbox.merge(new GeoBoundingBox(current, current));
			}
		}
		
		return bbox;
	}
}
